<template>
  <div class="login-container">
    <!-- 左侧：产品介绍区 -->
    <div class="left-section">
      <div class="brand-content">
        <!-- Logo区域 -->
        <div class="brand-header">
          <div class="brand-icon">
            <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
              <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z" fill="currentColor"/>
              <path d="M464 336h112v336H464zm-112 168h112v168H352zm224-112h112v280H576z" fill="currentColor"/>
            </svg>
          </div>
          <div class="brand-text">
            <h1 class="brand-title">加入BOSS直聘</h1>
            <p class="brand-subtitle">开启你的职业新旅程</p>
          </div>
        </div>

        <!-- 特色介绍卡片 -->
        <div class="features">
          <div class="feature-card">
            <div class="feature-icon boss-icon">
              <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                <path d="M512 512m-256 0a256 256 0 1 0 512 0 256 256 0 1 0-512 0Z" fill="currentColor"/>
                <path d="M768 768c0-141.385-114.615-256-256-256S256 626.615 256 768" fill="currentColor"/>
              </svg>
            </div>
            <div class="feature-content">
              <div class="feature-badge">BOSS直聘</div>
                <h3 class="feature-title">找工作，上BOSS直聘直接谈</h3>
                <p class="feature-desc">与老板直接沟通，跳过HR，快速找到心仪工作</p>
            </div>
          </div>

            <div class="feature-card">
            <div class="feature-icon chat-icon">
              <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                <path d="M664 512c0 88.366-93.11 160-208 160-114.89 0-208-71.634-208-160s93.11-160 208-160 208 71.634 208 160z" fill="currentColor"/>
                <path d="M925.248 353.504C893.44 194.24 765.44 64 599.136 64c-158.816 0-285.92 121.952-314.176 281.984C151.04 351.008 48 457.984 48 588.864c0 130.88 103.072 237.856 236.992 242.944.032 0 .064.192.096.192h312.384c169.472 0 306.688-137.216 306.688-306.688 0-97.472-45.28-184.48-116.224-240.736z" fill="currentColor"/>
              </svg>
            </div>
            <div class="feature-content">
              <h3 class="feature-title">在线沟通</h3>
              <p class="feature-desc">随时随地与HR或BOSS在线沟通，及时了解职位详情</p>
            </div>
          </div>

          <div class="feature-card">
            <div class="feature-icon job-icon">
              <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                <path d="M320 384h384v64H320zm0 128h384v64H320z" fill="currentColor"/>
                <path d="M832 128H192c-35.3 0-64 28.7-64 64v640c0 35.3 28.7 64 64 64h640c35.3 0 64-28.7 64-64V192c0-35.3-28.7-64-64-64zm0 704H192V192h640v640z" fill="currentColor"/>
              </svg>
            </div>
            <div class="feature-content">
              <h3 class="feature-title">职位丰富</h3>
              <p class="feature-desc">覆盖互联网、金融、教育等各大行业，职位任你挑</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧：登录表单区 -->
    <div class="right-section">
      <!-- APP扫码登录提示 -->
      <div class="app-login-tip">
        <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
          <path d="M744.727273 46.545455H279.272727c-62.836364 0-116.363636 53.527273-116.363636 116.363636v698.181818c0 62.836364 53.527273 116.363636 116.363636 116.363636h465.454546c62.836364 0 116.363636-53.527273 116.363636-116.363636V162.909091c0-62.836364-53.527273-116.363636-116.363636-116.363636z m34.909091 814.545454c0 18.618182-16.290909 34.909091-34.909091 34.909091H279.272727c-18.618182 0-34.909091-16.290909-34.909091-34.909091V162.909091c0-18.618182 16.290909-34.909091 34.909091-34.909091h465.454546c18.618182 0 34.909091 16.290909 34.909091 34.909091v698.181818z" fill="currentColor"/>
        </svg>
        <span>APP扫码登录</span>
      </div>

      <div class="login-card">
      <!-- 标题 -->
      <div class="login-header">
        <h1 class="page-title">验证码登录/注册</h1>
        <p class="page-subtitle">首次验证通过即注册BOSS直聘账号</p>
      </div>

      <!-- 用户角色选择 -->
      <div class="user-type-tabs">
          <button
          type="button"
          class="type-tab"
          :class="{ 'active': userType === 'jobseeker' }"
          @click="handleUserTypeChange('jobseeker')"
        >
          我要找工作
        </button>
        <button
          type="button"
          class="type-tab"
          :class="{ 'active': userType === 'recruiter' }"
          @click="handleUserTypeChange('recruiter')"
        >
          我要招聘
        </button>
      </div>

      <!-- 登录方式切换 -->
      <div class="login-method-tabs">
        <button
          type="button"
          class="method-tab"
          :class="{ 'active': loginMethod === 'password' }"
          @click="loginMethod = 'password'; phone = ''; username = ''; phoneError = ''"
        >
          账密登录
        </button>
          <button
          type="button"
          class="method-tab"
          :class="{ 'active': loginMethod === 'code' }"
          @click="loginMethod = 'code'; phone = ''; username = ''; phoneError = ''"
        >
          验证码登录
        </button>
      </div>

      <!-- 登录表单 -->
      <div class="login-form">
        <!-- 账号/手机号输入 -->
        <!-- 当选择招聘者+账密登录时，显示账号输入框；否则显示手机号输入框 -->
        <div class="form-group">
          <div class="input-wrapper" :class="{ 'has-error': phoneError, 'is-focus': phoneFocus }">
            <span class="input-icon">
              <!-- 如果是招聘者+账密登录，显示账号图标；否则显示手机图标 -->
              <svg v-if="userType === 'recruiter' && loginMethod === 'password'" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                <path d="M858.5 763.6c-18.9-44.8-46.1-85-80.6-119.5-34.5-34.5-74.7-61.6-119.5-80.6-0.4-0.2-0.8-0.3-1.2-0.5C719.5 518 760 489.8 796.2 456c0.2-0.2 0.4-0.3 0.6-0.5C826 428.9 848.5 396.9 863 362.1c18.3-43.9 27.5-91.4 27.5-140.1 0-159.1-129.5-288.5-288.5-288.5S313.5 62.9 313.5 222c0 48.7 9.2 96.2 27.5 140.1 14.5 34.8 37 66.8 66.2 93.5 0.2 0.2 0.4 0.3 0.6 0.5 36.2 33.8 76.7 62 138.8 107-44.8 18.9-85 46.1-119.5 80.6-34.5 34.5-61.6 74.7-80.6 119.5-0.2 0.4-0.3 0.8-0.5 1.2C165.5 518 136 489.8 99.8 456c-0.2-0.2-0.4-0.3-0.6-0.5C70 428.9 47.5 396.9 33 362.1 14.7 318.2 5.5 270.7 5.5 222c0-159.1 129.5-288.5 288.5-288.5S582.5 62.9 582.5 222c0 48.7-9.2 96.2-27.5 140.1-14.5 34.8-37 66.8-66.2 93.5-0.2 0.2-0.4 0.3-0.6 0.5-36.2 33.8-76.7 62-138.8 107 0.4 0.2 0.8 0.3 1.2 0.5 44.8 18.9 85 46.1 119.5 80.6 34.5 34.5 61.6 74.7 80.6 119.5 18.9 44.8 28.7 93.4 28.7 143.2v128.5h73v-128.5c0-49.8 9.8-98.4 28.7-143.2z" fill="currentColor"/>
              </svg>
              <svg v-else viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                <path d="M744.727273 46.545455H279.272727c-62.836364 0-116.363636 53.527273-116.363636 116.363636v698.181818c0 62.836364 53.527273 116.363636 116.363636 116.363636h465.454546c62.836364 0 116.363636-53.527273 116.363636-116.363636V162.909091c0-62.836364-53.527273-116.363636-116.363636-116.363636z m34.909091 814.545454c0 18.618182-16.290909 34.909091-34.909091 34.909091H279.272727c-18.618182 0-34.909091-16.290909-34.909091-34.909091V162.909091c0-18.618182 16.290909-34.909091 34.909091-34.909091h465.454546c18.618182 0 34.909091 16.290909 34.909091 34.909091v698.181818z" fill="currentColor"/>
                <path d="M512 744.727273m-34.909091 0a34.909091 34.909091 0 1 0 69.818182 0 34.909091 34.909091 0 1 0-69.818182 0Z" fill="currentColor"/>
              </svg>
            </span>
            <input
              v-if="userType === 'recruiter' && loginMethod === 'password'"
              v-model="username"
              type="text"
              placeholder="请输入账号"
              class="form-input"
              @focus="phoneFocus = true"
              @blur="phoneFocus = false"
            />
            <input
              v-else
              v-model="phone"
              type="tel"
              maxlength="11"
              placeholder="请输入手机号"
              class="form-input"
              @focus="phoneFocus = true"
              @blur="phoneFocus = false; validatePhone()"
            />
            <span v-if="(userType === 'recruiter' && loginMethod === 'password' && username) || ((userType !== 'recruiter' || loginMethod !== 'password') && phone)" class="clear-icon" @click="clearInput">
              <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm165.4 618.2l-66-0.3L512 563.4l-99.3 118.4-66.1 0.3c-4.4 0-8-3.5-8-8 0-1.9 0.7-3.7 1.9-5.2l130.1-155L340.5 359a8.32 8.32 0 0 1-1.9-5.2c0-4.4 3.6-8 8-8l66.1 0.3L512 464.6l99.3-118.4 66-0.3c4.4 0 8 3.5 8 8 0 1.9-0.7 3.7-1.9 5.2L553.5 514l130 155c1.2 1.5 1.9 3.3 1.9 5.2 0 4.4-3.6 8-8 8z" fill="currentColor"/>
              </svg>
            </span>
          </div>
          <div v-if="phoneError" class="error-message">{{ phoneError }}</div>
        </div>

        <!-- 密码输入（账密登录模式） -->
        <div v-if="loginMethod === 'password'" class="form-group">
          <div class="input-wrapper" :class="{ 'has-error': passwordError, 'is-focus': passwordFocus }">
            <span class="input-icon">
              <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                <path d="M832 464h-68V240c0-70.7-57.3-128-128-128H388c-70.7 0-128 57.3-128 128v224h-68c-17.7 0-32 14.3-32 32v384c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V496c0-17.7-14.3-32-32-32zM332 240c0-30.9 25.1-56 56-56h248c30.9 0 56 25.1 56 56v224H332V240zm460 600H232V536h560v304z" fill="currentColor"/>
                <path d="M484 701v53c0 4.4 3.6 8 8 8h40c4.4 0 8-3.6 8-8v-53c12.1-8.7 20-22.9 20-39 0-26.5-21.5-48-48-48s-48 21.5-48 48c0 16.1 7.9 30.3 20 39z" fill="currentColor"/>
              </svg>
            </span>
            <input
              v-model="password"
              type="password"
              placeholder="请输入密码"
              class="form-input"
              @focus="passwordFocus = true"
              @blur="passwordFocus = false"
              @keyup.enter="handleLogin"
            />
          </div>
          <div v-if="passwordError" class="error-message">{{ passwordError }}</div>
        </div>

        <!-- 验证码输入（验证码登录模式） -->
        <div v-if="loginMethod === 'code'" class="form-group">
          <div class="input-wrapper" :class="{ 'has-error': codeError, 'is-focus': codeFocus }">
            <span class="input-icon">
              <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                <path d="M832 464h-68V240c0-70.7-57.3-128-128-128H388c-70.7 0-128 57.3-128 128v224h-68c-17.7 0-32 14.3-32 32v384c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V496c0-17.7-14.3-32-32-32zM332 240c0-30.9 25.1-56 56-56h248c30.9 0 56 25.1 56 56v224H332V240zm460 600H232V536h560v304z" fill="currentColor"/>
                <path d="M484 701v53c0 4.4 3.6 8 8 8h40c4.4 0 8-3.6 8-8v-53c12.1-8.7 20-22.9 20-39 0-26.5-21.5-48-48-48s-48 21.5-48 48c0 16.1 7.9 30.3 20 39z" fill="currentColor"/>
              </svg>
            </span>
            <input
              v-model="code"
              type="text"
              maxlength="6"
              placeholder="请输入验证码"
              class="form-input"
              @focus="codeFocus = true"
              @blur="codeFocus = false"
              @keyup.enter="handleLogin"
            />
            <button
              class="code-btn"
              :class="{ 'disabled': countdown > 0 || !isPhoneValid }"
              :disabled="countdown > 0 || !isPhoneValid"
              @click="sendCode"
            >
              {{ countdown > 0 ? `${countdown}秒后重发` : '获取验证码' }}
            </button>
          </div>
          <div v-if="codeError" class="error-message">{{ codeError }}</div>
        </div>

        <!-- 记住密码和忘记密码 -->
        <div v-if="loginMethod === 'password'" class="password-actions">
          <label class="remember-password">
            <input v-model="rememberPassword" type="checkbox" />
            <span>记住密码</span>
          </label>
          <a href="#" class="forgot-password">忘记密码?</a>
        </div>

        <!-- 登录按钮 -->
        <button
          class="login-btn"
          :class="{ 'disabled': !canLogin }"
          :disabled="!canLogin || loading"
          @click="handleLogin"
        >
          <span v-if="loading" class="loading-spinner"></span>
          <span v-else>登录</span>
        </button>

        <!-- 用户协议 -->
        <div class="agreement">
          <label class="checkbox-wrapper">
            <input v-model="agreeTerms" type="checkbox" class="checkbox-input" />
            <span class="checkbox-custom"></span>
            <span class="checkbox-text">
              已阅读并同意BOSS直聘
              <a href="#" class="link">《用户协议》</a>
              <a href="#" class="link">《隐私政策》</a>
              ，允许BOSS直聘统一管理本人账号信息
            </span>
          </label>
        </div>

        <!-- 钉钉扫码登录 -->
        <button class="dingtalk-login-btn" @click="handleDingTalkLogin" type="button">
          <svg class="dingtalk-icon" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
            <circle cx="512" cy="512" r="448" fill="currentColor"/>
            <text x="512" y="650" font-size="480" font-weight="bold" fill="#ffffff" text-anchor="middle" font-family="Arial, Microsoft YaHei, sans-serif">钉</text>
          </svg>
          <span>钉钉扫码登录/注册</span>
        </button>
      </div>
      </div>
    </div>
  </div>

    <!-- Toast 提示 -->
    <transition name="toast">
      <div v-if="toast.show" class="toast" :class="toast.type">
        <span class="toast-icon">
          <svg v-if="toast.type === 'success'" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
            <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm193.5 301.7l-210.6 292a31.8 31.8 0 0 1-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z" fill="currentColor"/>
          </svg>
          <svg v-else viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
            <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm165.4 618.2l-66-0.3L512 563.4l-99.3 118.4-66.1 0.3c-4.4 0-8-3.5-8-8 0-1.9 0.7-3.7 1.9-5.2l130.1-155L340.5 359a8.32 8.32 0 0 1-1.9-5.2c0-4.4 3.6-8 8-8l66.1 0.3L512 464.6l99.3-118.4 66-0.3c4.4 0 8 3.5 8 8 0 1.9-0.7 3.7-1.9 5.2L553.5 514l130 155c1.2 1.5 1.9 3.3 1.9 5.2 0 4.4-3.6 8-8 8z" fill="currentColor"/>
          </svg>
        </span>
        <span class="toast-message">{{ toast.message }}</span>
      </div>
    </transition>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { sendVerificationCode, phoneLogin } from '../../api/auth'
import { useUserStore } from '../../stores/user'
import request from '../../api/request'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()

// 表单数据
const phone = ref('')
const username = ref('')  // 企业登录账号
const password = ref('')
const code = ref('')
const userType = ref('jobseeker')  // 用户角色：jobseeker(求职者) / recruiter(招聘者)
const loginMethod = ref('code')  // 登录方式：password(账密登录) / code(验证码登录)
const rememberPassword = ref(false)
const agreeTerms = ref(true)
const loading = ref(false)

// 焦点状态
const phoneFocus = ref(false)
const passwordFocus = ref(false)
const codeFocus = ref(false)

// 错误信息
const phoneError = ref('')
const passwordError = ref('')
const codeError = ref('')

// 验证码倒计时
const countdown = ref(0)
let countdownTimer = null

// Toast 提示
const toast = ref({
  show: false,
  message: '',
  type: 'success' // success | error
})

// 钉钉登录相关 - 已改为页面跳转方式，不再需要弹窗状态
// 验证手机号
const validatePhone = () => {
  phoneError.value = ''
  if (!phone.value) {
    return false
  }
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    phoneError.value = '请输入正确的手机号'
    return false
  }
  return true
}

// 判断手机号是否有效
const isPhoneValid = computed(() => {
  return /^1[3-9]\d{9}$/.test(phone.value)
})

// 判断是否可以登录
const canLogin = computed(() => {
  if (!agreeTerms.value) {
    return false
  }
  
  // 如果是招聘者+账密登录，验证账号和密码
  if (userType.value === 'recruiter' && loginMethod.value === 'password') {
    return username.value.trim().length > 0 && password.value.length >= 6
  }
  
  // 其他情况，验证手机号和验证码/密码
  if (!isPhoneValid.value) {
    return false
  }
  
  if (loginMethod.value === 'password') {
    return password.value.length >= 6
  } else {
    return code.value.length === 6
  }
})

// 清空输入框
const clearInput = () => {
  if (userType.value === 'recruiter' && loginMethod.value === 'password') {
    username.value = ''
  } else {
    phone.value = ''
    phoneError.value = ''
  }
}

// 处理用户角色切换
const handleUserTypeChange = (type) => {
  userType.value = type
  // 切换角色时清空输入
  phone.value = ''
  username.value = ''
  phoneError.value = ''
  console.log('🔄 用户切换角色:', type === 'recruiter' ? '招聘者' : '求职者')
  console.log('📍 登录后将跳转到:', type === 'recruiter' ? '/recruiter (RecruiterHome.vue)' : '/home (Home.vue)')
}

// 显示 Toast
const showToast = (message, type = 'success') => {
  toast.value = {
    show: true,
    message,
    type
  }
  setTimeout(() => {
    toast.value.show = false
  }, 3000)
}

// 发送验证码
const sendCode = async () => {
  if (!validatePhone()) {
    return
  }

  if (countdown.value > 0) {
    return
  }

  try {
    loading.value = true
    const response = await sendVerificationCode(phone.value)
    
    // Mock模式：直接显示验证码
    if (response.code) {
      showToast(`验证码：${response.code}（开发模式）`, 'success')
      console.log(`📱 验证码：${response.code}`)
    } else {
      showToast('验证码已发送，请查看手机', 'success')
    }
    
    // 开始倒计时
    countdown.value = 60
    countdownTimer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(countdownTimer)
      }
    }, 1000)
  } catch (error) {
    console.error('发送验证码失败', error)
    showToast(error.response?.data?.msg || '发送验证码失败，请稍后重试', 'error')
  } finally {
    loading.value = false
  }
}

// 企业登录函数
const enterpriseLogin = async (username, password) => {
  // 企业登录接口使用完整URL，与EnLogin.vue保持一致
  const response = await fetch('http://localhost:8000/enterprise/login/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ username, password })
  })
  
  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}))
    throw { response: { data: errorData } }
  }
  
  return response.json()
}

// 登录
const handleLogin = async () => {
  if (!canLogin.value || loading.value) {
    return
  }

  // 清空错误信息
  phoneError.value = ''
  codeError.value = ''
  passwordError.value = ''

  if (!agreeTerms.value) {
    showToast('请阅读并同意用户协议和隐私政策', 'error')
    return
  }

  try {
    loading.value = true
    
    // 判断是否是招聘者+账密登录，调用企业登录接口
    if (userType.value === 'recruiter' && loginMethod.value === 'password') {
      console.log('========================================')
      console.log('📝 开始企业登录流程（招聘者+账密登录）')
      console.log('========================================')
      console.log('👤 账号:', username.value)
      console.log('🔑 密码:', '***')
      console.log('👔 用户类型: 招聘者（企业端）')
      console.log('========================================')
      
      const data = await enterpriseLogin(username.value, password.value)
      
      if (data && data.status === 'success' && data.token) {
        // 保存token到localStorage和store
        localStorage.setItem('token', data.token)
        userStore.setTokens(data.token, '')
        
        console.log('✅ 企业登录成功')
        console.log('🔐 Token已保存')
        console.log('📋 信息完善状态:', data.is_complete)
        
        ElMessage.success('登录成功')
        
        // 根据is_complete字段判断跳转
        if (data.is_complete === false) {
          console.log('📍 跳转到完善招聘者信息页面: /enterprise/personal')
          router.push('/enterprise/personal')
        } else {
          console.log('📍 跳转到企业主页: /enterprise/main')
          router.push('/enterprise/main')
        }
      } else {
        const errorMsg = data?.error || '登录失败'
        passwordError.value = errorMsg
        ElMessage.error(errorMsg)
      }
      return
    }
    
    // 其他登录方式（手机号+验证码/密码）
    console.log('========================================')
    console.log('📝 开始登录流程')
    console.log('========================================')
    console.log('📱 手机号:', phone.value)
    console.log('🔑 验证码:', code.value)
    console.log('👤 用户选择的角色:', userType.value, `(${userType.value === 'recruiter' ? '招聘者' : '求职者'})`)
    console.log('📍 预期跳转页面:', userType.value === 'recruiter' ? '/recruiter (RecruiterHome.vue)' : '/home (Home.vue)')
    console.log('========================================')
    
    const response = await phoneLogin(phone.value, code.value, userType.value)
    
    console.log('✅ 登录API调用成功')
    console.log('📦 返回的用户数据:', response.user)
    console.log('🔐 返回的Token:', response.token?.substring(0, 20) + '...')
    
    // 保存用户信息和token
    userStore.login(response.user, response.token, response.refresh)
    
    // 等待一个微任务，确保 store 数据已更新
    await new Promise(resolve => setTimeout(resolve, 100))
    
    console.log('========================================')
    console.log('💾 数据已保存到Store和localStorage')
    console.log('========================================')
    console.log('✅ Store中的用户数据:', userStore.user)
    console.log('✅ Store中的user_type:', userStore.user?.user_type)
    console.log('✅ Store登录状态:', userStore.isLoggedIn)
    
    // 根据用户角色跳转到不同页面
    const targetRoute = userType.value === 'recruiter' ? '/recruiter' : '/home'
    const welcomeMsg = userType.value === 'recruiter' ? '招聘者登录成功！' : '求职者登录成功！'
    
    console.log('========================================')
    console.log('🚀 准备跳转')
    console.log('========================================')
    console.log('📍 目标路径:', targetRoute)
    console.log('📄 目标组件:', userType.value === 'recruiter' ? 'RecruiterHome.vue' : 'Home.vue')
    console.log('👤 用户角色:', userType.value === 'recruiter' ? '招聘者' : '求职者')
    console.log('========================================')
    
    showToast(welcomeMsg, 'success')
    
    // 使用 nextTick 确保所有更新完成后再跳转
    await router.replace(targetRoute)
    
    console.log('✅ 路由跳转命令已执行，当前路径:', router.currentRoute.value.path)
    
  } catch (error) {
    console.error('❌ 登录失败:', error)
    const errorMsg = error.response?.data?.error || error.response?.data?.msg || '登录失败，请检查账号和密码'
    if (userType.value === 'recruiter' && loginMethod.value === 'password') {
      passwordError.value = errorMsg
    } else {
      codeError.value = errorMsg
    }
    showToast(errorMsg, 'error')
  } finally {
    loading.value = false
  }
}

// 处理钉钉登录 - 跳转到专门的钉钉登录页面
const handleDingTalkLogin = () => {
  // 保存用户选择的角色到localStorage，回调后使用
  localStorage.setItem('dingtalk_user_type', userType.value)
  
  console.log('🔄 跳转到钉钉登录页面')
  console.log('👤 用户角色:', userType.value === 'recruiter' ? '招聘者' : '求职者')
  
  // 跳转到钉钉登录页面，并传递用户角色参数
  router.push({
    path: '/dingtalk-login',
    query: {
      userType: userType.value
    }
  })
}


// 组件卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.login-container {
  display: flex;
  min-height: 100vh;
  background: #f5f5f7;
}

/* ========== 左侧：产品介绍区 ========== */
.left-section {
  flex: 1;
  background: linear-gradient(135deg, #7c3aed 0%, #a855f7 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px;
  position: relative;
  overflow: hidden;
}

.left-section::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 1px, transparent 1px);
  background-size: 50px 50px;
  animation: moveBackground 20s linear infinite;
}

@keyframes moveBackground {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(50px, 50px);
  }
}

.brand-content {
  position: relative;
  z-index: 1;
  max-width: 500px;
  width: 100%;
}

.brand-header {
  margin-bottom: 60px;
}

.brand-icon {
  width: 64px;
  height: 64px;
  margin-bottom: 24px;
  color: #ffffff;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

.brand-icon svg {
  width: 100%;
  height: 100%;
  filter: drop-shadow(0 4px 12px rgba(0, 0, 0, 0.2));
}

.brand-title {
  font-size: 48px;
  font-weight: 700;
  color: #ffffff;
  margin-bottom: 12px;
  letter-spacing: 2px;
}

.brand-subtitle {
  font-size: 18px;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 400;
}

/* 特色卡片 */
.features {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.feature-card {
  display: flex;
  gap: 20px;
  padding: 28px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s;
}

.feature-card:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateX(8px);
}

.feature-icon {
  width: 56px;
  height: 56px;
  flex-shrink: 0;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
}

.feature-icon.boss-icon {
  background: rgba(255, 255, 255, 0.2);
}

.feature-icon.chat-icon {
  background: rgba(255, 255, 255, 0.2);
}

.feature-icon.job-icon {
  background: rgba(255, 255, 255, 0.2);
}

.feature-icon svg {
  width: 32px;
  height: 32px;
}

.feature-content {
  flex: 1;
}

.feature-badge {
  display: inline-block;
  padding: 4px 12px;
  background: rgba(255, 255, 255, 0.25);
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  color: #ffffff;
  margin-bottom: 12px;
}

.feature-title {
  font-size: 20px;
  font-weight: 600;
  color: #ffffff;
  margin-bottom: 8px;
}

.feature-desc {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.85);
  line-height: 1.6;
}

/* ========== 右侧：登录表单区 ========== */
.right-section {
  flex: 0 0 540px;
  background: #ffffff;
  display: flex;
  flex-direction: column;
  position: relative;
}

.app-login-tip {
  position: absolute;
  top: 24px;
  right: 24px;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  transition: color 0.3s;
}

.app-login-tip:hover {
  color: #7c3aed;
}

.app-login-tip svg {
  width: 18px;
  height: 18px;
}

.login-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 80px 60px 40px;
  overflow-y: auto;
}

/* 登录头部 */
.login-header {
  margin-bottom: 40px;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #1a1a1a;
  margin-bottom: 8px;
}

.page-subtitle {
  font-size: 14px;
  color: #999;
}

/* 用户角色选择 */
.user-type-tabs {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
}

.type-tab {
  flex: 1;
  padding: 12px 20px;
  background: #f5f5f7;
  border: 2px solid transparent;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 500;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;
}

.type-tab:hover {
  background: #e9e9eb;
}

.type-tab.active {
  background: #ffffff;
  border-color: #7c3aed;
  color: #7c3aed;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(124, 58, 237, 0.2);
}

/* 角色选择提示 */
.role-hint {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f5ff 100%);
  border: 1px solid #91d5ff;
  border-radius: 8px;
  margin-top: 16px;
  margin-bottom: 16px;
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.hint-icon {
  font-size: 18px;
}

.hint-text {
  font-size: 13px;
  color: #0050b3;
  line-height: 1.5;
}

.hint-text strong {
  color: #003a8c;
  font-weight: 600;
}

/* 登录方式切换 */
.login-method-tabs {
  display: flex;
  border-bottom: 1px solid #e5e5e7;
  margin-bottom: 32px;
}

.method-tab {
  position: relative;
  padding: 12px 0;
  margin-right: 32px;
  background: transparent;
  border: none;
  font-size: 15px;
  font-weight: 500;
  color: #999;
  cursor: pointer;
  transition: color 0.3s;
}

.method-tab:hover {
  color: #7c3aed;
}

.method-tab.active {
  color: #7c3aed;
}

.method-tab.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 2px;
  background: #7c3aed;
}

/* 表单 */
.login-form {
  width: 100%;
}

.form-group {
  margin-bottom: 24px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  background: #f7f8fa;
  border: 2px solid transparent;
  border-radius: 12px;
  transition: all 0.3s ease;
  overflow: hidden;
}

.input-wrapper.is-focus {
  background: #ffffff;
  border-color: #7c3aed;
  box-shadow: 0 0 0 4px rgba(124, 58, 237, 0.1);
}

.input-wrapper.has-error {
  border-color: #ff4d4f;
  background: #fff1f0;
}

.input-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 16px;
  color: #999;
}

.input-icon svg {
  width: 20px;
  height: 20px;
}

.form-input {
  flex: 1;
  height: 52px;
  border: none;
  background: transparent;
  font-size: 15px;
  color: #1a1a1a;
  outline: none;
  padding-right: 16px;
}

.form-input::placeholder {
  color: #bbb;
}

.clear-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  margin-right: 16px;
  cursor: pointer;
  color: #bbb;
  transition: color 0.3s;
}

.clear-icon:hover {
  color: #666;
}

.clear-icon svg {
  width: 16px;
  height: 16px;
}

.code-btn {
  height: 36px;
  padding: 0 16px;
  margin-right: 8px;
  background: #00c48f;
  color: #ffffff;
  border: none;
  border-radius: 8px;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s;
}

.code-btn:hover:not(.disabled) {
  background: #00b380;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 196, 143, 0.3);
}

.code-btn.disabled {
  background: #e0e0e0;
  color: #999;
  cursor: not-allowed;
}

.error-message {
  margin-top: 8px;
  padding-left: 16px;
  font-size: 13px;
  color: #ff4d4f;
  animation: shake 0.3s;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

/* 密码操作区域 */
.password-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.remember-password {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
}

.remember-password input[type="checkbox"] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.forgot-password {
  font-size: 14px;
  color: #7c3aed;
  text-decoration: none;
  transition: color 0.3s;
}

.forgot-password:hover {
  color: #a855f7;
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  height: 48px;
  background: linear-gradient(135deg, #7c3aed 0%, #a855f7 100%);
  color: #ffffff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  letter-spacing: 1px;
}

.login-btn:hover:not(.disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(124, 58, 237, 0.4);
}

.login-btn:active:not(.disabled) {
  transform: translateY(0);
}

.login-btn.disabled {
  background: #e5e5e7;
  color: #999;
  cursor: not-allowed;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top-color: #ffffff;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 用户协议 */
.agreement {
  margin-top: 24px;
  margin-bottom: 16px;
}

.checkbox-wrapper {
  display: flex;
  align-items: flex-start;
  cursor: pointer;
  user-select: none;
}

.checkbox-input {
  flex-shrink: 0;
  width: 16px;
  height: 16px;
  margin-right: 8px;
  cursor: pointer;
}

.checkbox-custom {
  position: relative;
  width: 16px;
  height: 16px;
  border: 2px solid #d9d9d9;
  border-radius: 4px;
  margin-right: 8px;
  transition: all 0.3s;
  flex-shrink: 0;
}

.checkbox-input:checked ~ .checkbox-custom {
  background: #7c3aed;
  border-color: #7c3aed;
}

.checkbox-input:checked ~ .checkbox-custom::after {
  content: '';
  position: absolute;
  left: 4px;
  top: 1px;
  width: 4px;
  height: 8px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.checkbox-text {
  font-size: 12px;
  color: #999;
  line-height: 1.6;
}

.link {
  color: #7c3aed;
  text-decoration: none;
  transition: color 0.3s;
  margin: 0 2px;
}

.link:hover {
  color: #a855f7;
  text-decoration: underline;
}

/* 钉钉登录按钮 */
.dingtalk-login-btn {
  width: 100%;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background: #ffffff;
  border: 1px solid #e5e5e7;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 500;
  color: rgb(0, 112, 192);
  cursor: pointer;
  transition: all 0.3s;
}

.dingtalk-login-btn:hover {
  border-color: rgb(0, 112, 192);
  background: #f0f9ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 112, 192, 0.1);
}

.dingtalk-icon {
  width: 24px;
  height: 24px;
  color: rgb(0, 112, 192);
}


/* Toast 提示 */
.toast {
  position: fixed;
  top: 80px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 9999;
  display: flex;
  align-items: center;
  padding: 12px 24px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  font-size: 14px;
  font-weight: 500;
}

.toast.success {
  color: #00c48f;
}

.toast.error {
  color: #ff4d4f;
}

.toast-icon {
  display: flex;
  margin-right: 8px;
}

.toast-icon svg {
  width: 20px;
  height: 20px;
}

.toast-enter-active,
.toast-leave-active {
  transition: all 0.3s ease;
}

.toast-enter-from {
  opacity: 0;
  transform: translateX(-50%) translateY(-20px);
}

.toast-leave-to {
  opacity: 0;
  transform: translateX(-50%) translateY(-20px);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .left-section {
    flex: 0 0 400px;
    padding: 40px;
  }

  .brand-title {
    font-size: 36px;
  }

  .feature-card {
    padding: 20px;
  }

  .feature-title {
    font-size: 18px;
  }

  .right-section {
    flex: 1;
  }
}

@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
  }

  .left-section {
    flex: none;
    min-height: 50vh;
    padding: 40px 24px;
  }

  .brand-title {
    font-size: 32px;
  }

  .features {
    display: none;
  }

  .right-section {
    flex: none;
    flex: 1;
  }

  .login-card {
    padding: 40px 24px;
  }

  .page-title {
    font-size: 24px;
  }

  .app-login-tip {
    top: 16px;
    right: 16px;
    font-size: 12px;
  }

  .type-tab {
    font-size: 14px;
    padding: 10px 16px;
  }

  .method-tab {
    font-size: 14px;
  }

  .code-btn {
    font-size: 12px;
    padding: 0 12px;
  }
}

@media (max-width: 480px) {
  .brand-header {
    margin-bottom: 30px;
  }

  .brand-title {
    font-size: 28px;
  }

  .brand-subtitle {
    font-size: 16px;
  }

  .login-card {
    padding: 30px 20px;
  }

  .page-title {
    font-size: 20px;
  }

  .user-type-tabs {
    gap: 12px;
  }

  .type-tab {
    font-size: 13px;
    padding: 8px 12px;
  }

  .method-tab {
    font-size: 13px;
    margin-right: 24px;
  }

  .checkbox-text {
    font-size: 11px;
  }

  .app-login-tip span {
    display: none;
  }
}
</style>


